'use strict'

const { ApiController } = require('jax')

class DemoTypeController extends ApiController {
  get Model() {
    return this.ctx.model.DemoCategory
  }

  async tree() {
    const { ctx } = this
    const { query, helper } = ctx

    const where = {}

    ;['isOpen'].map((key) => {
      if (query[key] && !query[key] == '') where[key] = query[key]
    })

    if (query.keyword && !query.keyword == '') where.title = new RegExp(helper.toMongoRegex(query.keyword), 'i')

    const returnData = await this.Model.tree({
      where,
      sort: {
        isTop: 'DESC',
        rank: 'ASC',
      },
    })

    ctx.body = {
      code: 0,
      msg: 'success',
      data: returnData,
    }
  }

  async index() {
    const { ctx } = this
    const { query, helper } = ctx

    const filter = {}

    ;['isOpen', 'systemType'].map((key) => {
      if (query[key] && !query[key] == '') filter[key] = query[key]
    })

    if (query.keyword && !query.keyword == '') filter.title = new RegExp(helper.toMongoRegex(query.keyword), 'i')

    const returnData = await this.Model.flatTree({
      filter,
      sort: {
        isTop: 'DESC',
        rank: 'ASC',
      },
    })

    ctx.body = {
      code: 0,
      msg: 'success',
      data: returnData,
    }
  }
}

module.exports = DemoTypeController
